import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';
import { Message } from '@alifd/next';
import { t } from '@lingui/macro';

export default class TransferStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  data = [];
  issues = [];
  transfers = [];
  authInfo = null;

  loading = false;
  _tabStatus = '1';
  _orderStatus = '0';

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      this.data = yield api.search({ search, pg });
    } catch (error) {
      Message.error({ content: t`请求失败：${error}` });
      throw error;
    } finally {
      this.loading = false;
    }
  }

  * create(args) {
    yield api.create(args);
    yield this.query();
  }

  * update(args) {
    yield api.update(args);
    yield this.query();
  }

  * getGroup(args) {
    const res = yield api.getGroup(args);
    return res.map((p) => ({
      label: p.groupName,
      value: p.groupId,
    }));
  }

  * getMember(args) {
    const res = yield api.getMember(args);
    return res.map((p) => ({
      label: p.fullname,
      value: p.phone,
    }));
  }

  * get(id) {
    return yield api.get(id);
  }

  * getGroupId(id) {
    return yield api.getGroupId(id);
  }

  * groupUpdate(id) {
    yield api.groupUpdate(id);
    yield this.query();
  }

  * cancelTransaction(id) {
    yield api.cancelTransaction(id);
    yield this.query();
  }

  * getUser({ search, pg }) {
    const issue = yield api.getGroupId(rootStore.ruleStore._group_id);
    this.authInfo = this.getAuthInfo(issue);
    const assembleIssue = this.assembleIssue(issue);
    const transfer = yield api.getMember({ search, pg });
    const tempTransfer = transfer.map((p) => ({ label: `${p.memberId}-${p.nickname}(积分：${p.points})`, nickname: p.nickname, value: p.memberId, phone: p.phone, memberPoints: p.points }));
    this.issues = observable(assembleIssue);
    this.transfers = observable(tempTransfer);
    return assembleIssue;
  }

  assembleIssue(data) {
    const temp = [];
    const { accountingName, accountingId, accountingPhone, managerId, managerName, managerPhone } = data;
    temp.push({
      label: `群管理：${managerName}`,
      value: managerId,
      phone: managerPhone,
    });
    temp.push({
      label: `会计：${accountingName}`,
      value: accountingId,
      phone: accountingPhone,
    });
    temp.push({
      label: '管理员',
      value: 'admin@mzd',
      phone: 'admin',
    });
    return temp;
  }

  getAuthInfo(obj) {
    let issueId = '';
    let issueName = '';
    let issuePhone = '';
    const { username } = toJS(global?.me);
    const {
      managerId, managerName, managerPhone,
      accountingId, accountingName, accountingPhone,
    } = obj;
    if (username === managerId) {
      issueId = managerId;
      issueName = `群管理：${managerName}`;
      issuePhone = managerPhone;
    } else if (username === accountingId) {
      issueId = accountingId;
      issueName = `会计：${accountingName}`;
      issuePhone = accountingPhone;
    } else {
      issueId = 'admin@mzd';
      issueName = '管理员';
      issuePhone = 'admin';
    }
    return { issueId, issueName, issuePhone };
  }

  getIssueInfos(username) {
    let data = null;
    const findData = this.issues.find((e) => e.value === username);
    if (findData) {
      data = findData;
    }
    return data || {};
  }

  getTransferInfos(username) {
    let data = null;
    const findData = this.transfers.find((e) => e.value === username);
    if (findData) {
      data = findData;
    }
    return data || {};
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }

  get tab_Status() {
    return this._tabStatus;
  }

  set tab_Status(value) {
    this._tabStatus = value;
  }


  get orderStatus() {
    return this._orderStatus;
  }

  set orderStatus(value) {
    this._orderStatus = value;
    this._args.pg.page = 0;
    this.query({ page: 0 });
  }
}
